package com.wwwarehouse.taskcenter.fragment.job_point.step7;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.JobPointRuleDetailsResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.constant.job_point.TaskCenterCommon;
import com.wwwarehouse.taskcenter.custom_view.NewLineFlexLayout;
import com.wwwarehouse.taskcenter.eventbus_event.JobPointRuleEvent;
import com.wwwarehouse.taskcenter.tools.UserCenterCheckUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.taskcenter.fragment.job_point.AddJobPointCardFragment.KEY_BUSINESS_ID;
import static com.wwwarehouse.taskcenter.fragment.job_point.step7.ChooseAddWayRuleTemplateDetailsFragment.KEY_TEMPLATE_ID;

/**
 * Created by Jackie on 2017/11/13.
 * 设置作业点规则 选择添加方式 添加作业点规则
 */

public class ChooseAddWayAddRuleFragment extends BaseFragment implements View.OnClickListener {
    private View mRootView;

    private EditText mNameEdt;

    private ImageView mStartImg;
    private ImageView mEndImg;

    private NewLineFlexLayout mStartNewLineLayout;
    private NewLineFlexLayout mEndNewLineLayout;

    private LinearLayout mStartDetailsLayout;
    private LinearLayout mEndDetailsLayout;

    private Button mStartDetailsBtn;
    private Button mStartResetBtn;
    private Button mEndDetailsBtn;
    private Button mEndResetBtn;

    private Button mSaveBtn;

    private String mBusinessId;
    private String mTemplateId;

    private ChooseAddWayByRuleReceiver mReceiver;

    private static final int REQUEST_SAVE_RULE = 0;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_choose_add_way_add_rule, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mNameEdt = findView(mRootView, R.id.et_name);
        mNameEdt.setFilters(new InputFilter[] { UserCenterCheckUtils.limitLength(30) });

        mStartImg = findView(mRootView, R.id.iv_plus_start);
        mEndImg = findView(mRootView, R.id.iv_plus_end);

        mStartNewLineLayout = findView(mRootView, R.id.flex_layout_start);
        mEndNewLineLayout = findView(mRootView, R.id.flex_layout_end);

        mStartDetailsLayout = findView(mRootView, R.id.ll_details_start);
        mEndDetailsLayout = findView(mRootView, R.id.ll_details_end);

        mStartDetailsBtn = findView(mRootView, R.id.btn_details_start);
        mStartResetBtn = findView(mRootView, R.id.btn_reset_start);
        mEndDetailsBtn = findView(mRootView, R.id.btn_details_end);
        mEndResetBtn = findView(mRootView, R.id.btn_reset_end);

        mSaveBtn = findView(mRootView, R.id.btn_save);
    }

    private void initData() {
        TaskCenterCommon.getInstance().setStart(false);
        TaskCenterCommon.getInstance().setDetails(false);
        TaskCenterCommon.getInstance().setStartMap(null);
        TaskCenterCommon.getInstance().setEndMap(null);

        Bundle bundle = getArguments();

        if (bundle != null) {
            mBusinessId = bundle.getString(KEY_BUSINESS_ID);
            mTemplateId = bundle.getString(KEY_TEMPLATE_ID);
        }
    }

    private void initEvent() {
        mNameEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                checkSaveEnable();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mStartImg.setOnClickListener(this);
        mEndImg.setOnClickListener(this);

        mStartDetailsBtn.setOnClickListener(this);
        mStartResetBtn.setOnClickListener(this);
        mEndDetailsBtn.setOnClickListener(this);
        mEndResetBtn.setOnClickListener(this);

        mSaveBtn.setOnClickListener(this);

        mReceiver = new ChooseAddWayByRuleReceiver();
        mActivity.registerReceiver(mReceiver, new IntentFilter("ChooseAddWayAddRuleByBusiness"));
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseAddWayAddRuleFragment) {
            mActivity.setTitle(R.string.add_job_point_rule);
        }
    }

    @Override
    public void requestDatas() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.iv_plus_start) {
            TaskCenterCommon.getInstance().setStart(true);
            TaskCenterCommon.getInstance().setDetails(false);

            pushFragment(new ChooseAddWayAddRuleByBusinessFragment());
        } else if (id == R.id.iv_plus_end) {
            TaskCenterCommon.getInstance().setStart(false);
            TaskCenterCommon.getInstance().setDetails(false);

            pushFragment(new ChooseAddWayAddRuleByBusinessFragment());
        } else if (id == R.id.btn_details_start) {
            TaskCenterCommon.getInstance().setStart(true);
            TaskCenterCommon.getInstance().setDetails(true);

            pushFragment(new ChooseAddWayAddRuleByBusinessFragment());
        } else if (id == R.id.btn_reset_start) {
            mStartNewLineLayout.removeAllViews();

            mStartImg.setVisibility(View.VISIBLE);
            mStartDetailsLayout.setVisibility(View.GONE);

            TaskCenterCommon.getInstance().setStartMap(null);

            checkSaveEnable();
        } else if (id == R.id.btn_details_end) {
            TaskCenterCommon.getInstance().setStart(false);
            TaskCenterCommon.getInstance().setDetails(true);

            pushFragment(new ChooseAddWayAddRuleByBusinessFragment());
        } else if (id == R.id.btn_reset_end) {
            mEndNewLineLayout.removeAllViews();

            mEndImg.setVisibility(View.VISIBLE);
            mEndDetailsLayout.setVisibility(View.GONE);

            TaskCenterCommon.getInstance().setEndMap(null);

            checkSaveEnable();
        } else if (id == R.id.btn_save) {
            saveRule();
        }
    }

    /**
     * 保存规则
     */
    private void saveRule() {
        showProgressDialog(mActivity.getString(R.string.saving));

        Map map = new HashMap();

        map.put("buId", mBusinessId);

        Map startMap = TaskCenterCommon.getInstance().getStartMap();
        Map endMap = TaskCenterCommon.getInstance().getEndMap();

        JobPointRuleDetailsResponseBean.ContentBean contentBean = new JobPointRuleDetailsResponseBean.ContentBean();

        if (startMap != null && startMap.get("list") != null) {
            contentBean.setUnCoexistence((List<JobPointRuleDetailsResponseBean.ContentBean.UnCoexistenceBean>) startMap.get("list"));
        }

        if (endMap != null && endMap.get("list") != null) {
            contentBean.setCoexistence((List<JobPointRuleDetailsResponseBean.ContentBean.CoexistenceBean>) endMap.get("list"));
        }

        map.put("content", contentBean);
        map.put("tempId", mTemplateId);
        map.put("tempInstanceName", mNameEdt.getText().toString());

        NoHttpUtils.httpPost(TaskCenterConstant.URL_SAVE_RULE, map, mOnResponseListener, REQUEST_SAVE_RULE);
    }

    private void checkSaveEnable() {
        if ((!TextUtils.isEmpty(mNameEdt.getText().toString())) && ((TaskCenterCommon.getInstance().getStartMap() != null && TaskCenterCommon.getInstance().parseStartMap().size() > 0) ||
                (TaskCenterCommon.getInstance().getEndMap() != null && TaskCenterCommon.getInstance().parseEndMap().size() > 0))) {
            mSaveBtn.setEnabled(true);
        } else {
            mSaveBtn.setEnabled(false);
        }
    }

    private class ChooseAddWayByRuleReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if ("ChooseAddWayAddRuleByBusiness".equals(action)) {
                if (TaskCenterCommon.getInstance().isStart()) {
                    mStartNewLineLayout.removeAllViews();

                    if (TaskCenterCommon.getInstance().parseStartMap().size() > 0) {
                        mStartImg.setVisibility(View.GONE);
                        mStartDetailsLayout.setVisibility(View.VISIBLE);

                        for (TaskCenterCommon.TaskCenterBean taskCenterBean : TaskCenterCommon.getInstance().parseStartMap()) {
                            TextView textView = new TextView(mActivity);
                            textView.setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT));
                            textView.setText(taskCenterBean.getValue() + " ");
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
                            textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                            mStartNewLineLayout.addView(textView);
                        }
                    } else {
                        mStartImg.setVisibility(View.VISIBLE);
                        mStartDetailsLayout.setVisibility(View.GONE);
                    }
                } else {
                    mEndNewLineLayout.removeAllViews();

                    if (TaskCenterCommon.getInstance().parseEndMap().size() > 0) {
                        mEndImg.setVisibility(View.GONE);
                        mEndDetailsLayout.setVisibility(View.VISIBLE);

                        for (TaskCenterCommon.TaskCenterBean taskCenterBean : TaskCenterCommon.getInstance().parseEndMap()) {
                            TextView textView = new TextView(mActivity);
                            textView.setLayoutParams(new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT, ViewGroup.MarginLayoutParams.WRAP_CONTENT));
                            textView.setText(taskCenterBean.getValue() + " ");
                            textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
                            textView.setTextColor(mActivity.getResources().getColor(R.color.common_color_c7_96999e));

                            mEndNewLineLayout.addView(textView);
                        }
                    } else {
                        mEndImg.setVisibility(View.VISIBLE);
                        mEndDetailsLayout.setVisibility(View.GONE);
                    }
                }

               checkSaveEnable();
            }
        }
    }

    private NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_SAVE_RULE:
                    if ("0".equals(commonClass.getCode())) {
                        // 保存规则成功 返回到选择作业点规则页面
                        popFragment();
                        popFragment();

                        EventBus.getDefault().post(new JobPointRuleEvent(""));
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String s, int i) {
            toast(s);
        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };
}
